﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
/// <summary>
/// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
/// </summary>
public class AudioSystem : MonoBehaviour
{
    /// <summary>
    /// 锟斤拷前锟斤拷锟斤拷锟斤拷锟街碉拷址
    /// </summary>
    private string curBgmUrl;
    /// <summary>
    /// 锟斤拷锟斤拷锟斤拷效
    /// </summary>
    private AudioSource bgmSource;
    /// <summary>
    /// 锟斤拷效锟斤拷频锟斤拷锟斤拷
    /// </summary>
    private List<AudioSource> effectAudioList;
    /// <summary>
    /// 锟斤拷锟节诧拷锟脚碉拷锟斤拷频锟斤拷锟斤拷
    /// </summary>
    private List<AudioSource> playingAudioList;

    /// <summary>
    /// 锟斤拷锟节诧拷锟脚碉拷锟斤拷频url锟斤拷址
    /// </summary>
    private List<string> playingUrlList;
    public static AudioSystem Instance;
    private float EffectAudioVolume = 0;

    // Use this for initialization
    void Awake()
    {
        Instance = this;

        GlobalUserItem.EffectAudioVolume = PlayerPrefs.GetFloat(Key.EffectVolume, 1);
        GlobalUserItem.BGMVolume = PlayerPrefs.GetFloat(Key.MusicVolume, 1);


        bgmSource = GetComponent<AudioSource>();
        bgmSource.volume = GlobalUserItem.BGMVolume;
        effectAudioList = new List<AudioSource>();
        var effectAudio1 = transform.Find("EffectAudio1").GetComponent<AudioSource>();
        var effectAudio2 = transform.Find("EffectAudio2").GetComponent<AudioSource>();
        effectAudioList.Add(effectAudio1);
        effectAudioList.Add(effectAudio2);
        effectAudio1.volume = EffectAudioVolume;
        effectAudio2.volume = EffectAudioVolume;
        playingAudioList = new List<AudioSource>();
        playingUrlList = new List<string>();
    }



    // Update is called once per frame
    void Update()
    {

    }
    public void PlayBgmAsync(string abname, string assetname)
    {
        //AudioClip prefab =await ResourceManager.Instance.LoadAudioAsync(abname, assetname);
        //PlayBgmMusic(prefab);
        Debug.LogError("播放背景音乐");
        PlayBgm(abname, assetname);
    }
    public  void PlayBgm(string abname, string assetname)
    {
        Debug.LogError("播放背景音乐2222");
        AudioClip prefab =ResourceManager.Instance.LoadAudio(abname, assetname);
        PlayBgmMusic(prefab);
    }
    public void PlayEffectAsync(string abname, string assetname, bool isLoop = false)
    {
        PlayEffect(abname, assetname, isLoop);
    }
    public void PlayEffect(string abname, string assetname, bool isLoop = false)
    {
        AudioClip prefab =  ResourceManager.Instance.LoadAudio(abname, assetname);
        PlayEffectClip(prefab,isLoop);
    }

    //鎾?斁鎸夐挳闊虫晥 姝ｅ父鐨勬寜閽?煶鏁囂
    public void OnPlayBtn()
    {
        PlayEffect("Hall/Audios", "ButtonClick");
    }
    public void OnPlayBGM()
    {
        PlayBgm("Hall/Audios", "GameBgm");
    }

    /// <summary>
    /// 播放bgm
    /// </summary>
    /// <param name="clip"></param>
    public void PlayBgmMusic(AudioClip clip)
    {
        bgmSource.clip = clip;
        bgmSource.volume = 1;
        bgmSource.Play();
    }

    public void PlayEffectClip(AudioClip clip, bool isLoop)
    {
        if (clip != null)
        {
            StartCoroutine(PlayEffectAudioLua(clip,0, isLoop));
        }
    }
    public IEnumerator PlayEffectAudioLua(AudioClip clip, float delayTime = 0, bool isLoop = false)
    {

        if (clip != null)
        {
            if (delayTime > 0)
            {
                yield return new WaitForSeconds(delayTime);
            }
            AudioSource playAudioSource;
            if (effectAudioList.Count > 0)
            {
                playAudioSource = effectAudioList[0];
                effectAudioList.RemoveAt(0);
            }
            else
            {
                var audioObj = new GameObject();
                audioObj.transform.SetParent(transform);
                playAudioSource = audioObj.AddComponent<AudioSource>();
                playAudioSource.loop = false;
            }
            playAudioSource.volume = EffectAudioVolume;
            playingAudioList.Add(playAudioSource);
            playingUrlList.Add(clip.name);
            playAudioSource.clip = clip;
            playAudioSource.loop = isLoop;
            playAudioSource.Play();
            if (!isLoop)
            {
                yield return new WaitForSeconds(clip.length);
                playingAudioList.Remove(playAudioSource);
                playingUrlList.Remove(clip.name);
                effectAudioList.Add(playAudioSource);
            }
        }
    }
    /// <summary>
    /// 锟斤拷锟斤拷锟斤拷频
    /// </summary>
    /// <param name="clip"></param>
    /// <returns></returns>
    public IEnumerator PlayEffectAudio(string clipUrl, float delayTime = 0, bool isLoop = false)
    {
        Debug.Log("SHAO " + "PlayEffectAudio clipUrl = " + clipUrl);
        Debug.Log("SHAO " + "PlayEffectAudio " + EffectAudioVolume);
        AudioClip clip = Resources.Load<AudioClip>(clipUrl);
        if (clip != null)
        {
            if (delayTime > 0)
            {
                yield return new WaitForSeconds(delayTime);
            }
            AudioSource playAudioSource;
            if (effectAudioList.Count > 0)
            {
                playAudioSource = effectAudioList[0];
                effectAudioList.RemoveAt(0);
            }
            else
            {
                var audioObj = new GameObject();
                audioObj.transform.SetParent(transform);
                playAudioSource = audioObj.AddComponent<AudioSource>();
                playAudioSource.loop = false;
            }
            playAudioSource.volume = EffectAudioVolume;
            playingAudioList.Add(playAudioSource);
            playingUrlList.Add(clipUrl);
            playAudioSource.clip = clip;
            playAudioSource.loop = isLoop;
            playAudioSource.Play();
            if (!isLoop)
            {
                yield return new WaitForSeconds(clip.length);
                playingAudioList.Remove(playAudioSource);
                playingUrlList.Remove(clipUrl);
                effectAudioList.Add(playAudioSource);
            }
        }
    }

    /// <summary>
    /// 锟斤拷前锟斤拷锟节诧拷锟脚碉拷锟斤拷锟斤拷锟斤拷效
    /// </summary>
    public AudioSource curChatAudioSource;
    /// <summary>
    /// 锟斤拷锟斤拷指锟斤拷锟斤拷锟斤拷
    /// </summary>
    /// <param name="clip"></param>
    /// <returns></returns>
    public IEnumerator PlayEffectAudio(AudioClip clip)
    {
        curChatAudioSource = null;
        if (effectAudioList.Count > 0)
        {
            curChatAudioSource = effectAudioList[0];
            effectAudioList.RemoveAt(0);
        }
        else
        {
            var audioObj = new GameObject();
            audioObj.transform.SetParent(transform);
            curChatAudioSource = audioObj.AddComponent<AudioSource>();
            curChatAudioSource.loop = false;
        }
        curChatAudioSource.volume = EffectAudioVolume;
        playingAudioList.Add(curChatAudioSource);
        playingUrlList.Add("");
        curChatAudioSource.clip = clip;
        curChatAudioSource.Play();
        yield return new WaitForSeconds(clip.length);
        playingAudioList.Remove(curChatAudioSource);
        playingUrlList.Remove("");
        effectAudioList.Add(curChatAudioSource);
        curChatAudioSource = null;
    }

    /// <summary>
    /// 停止锟斤拷效锟斤拷锟斤拷
    /// </summary>
    /// <param name="clipUrl"></param>
    /// <returns></returns>
    public void StopEffectAudio(string clipUrl)
    {
        var clipIndex = playingUrlList.IndexOf(clipUrl);
        var idx = 0;
        Debug.Log("StopEffectAudio clipIndex = " + clipIndex);
        if (clipIndex != -1)
        {
            var playAudioSource = playingAudioList[clipIndex];
            if (playAudioSource.clip.name != clipUrl)
            {
                for (int i = 0; i < playingAudioList.Count; i++)
                {
                    Debug.Log(i+"name=============" + playingAudioList[i].clip.name + "======clipUrl========" + clipUrl);
                    if (playingAudioList[i].clip.name== clipUrl)
                    {
                        idx = i;
                    }
                }
                playAudioSource = playingAudioList[idx];
            }
            playAudioSource.Stop();
            playingUrlList.RemoveAt(clipIndex);
            effectAudioList.Add(playAudioSource);
        }
        
    }

    /// <summary>
    /// 停止锟斤拷锟斤拷锟斤拷锟斤拷
    /// </summary>
    public void StopAllAudio()
    {
        foreach (AudioSource audioSource in playingAudioList)
        {
            audioSource.Stop();
            effectAudioList.Add(audioSource);
        }
        playingAudioList.Clear();
        playingUrlList.Clear();
        StopAllCoroutines();
    }

    /// <summary>
    /// 锟斤拷锟矫憋拷锟斤拷锟斤拷锟斤拷锟斤拷小
    /// </summary>
    public void SetBgmAudioVolume(float volume)
    {
        GlobalUserItem.BGMVolume = volume;
        bgmSource.volume = volume;
    }

    /// <summary>
    /// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷小
    /// </summary>
    public void SetTalkAudioVolume(float volume)
    {
        //GlobleData.TalkVolume = volume;
        // bgmSource.volume = volume;
    }

    /// <summary>
    /// 锟斤拷停锟斤拷锟斤拷锟斤拷锟斤拷
    /// </summary>
    public void PauseBgm()
    {
        bgmSource.Pause();
    }

    /// <summary>
    /// 锟街革拷锟斤拷锟斤拷锟斤拷锟斤拷
    /// </summary>
    public void ResumeBgm()
    {
        bgmSource.Play();
    }

    /// <summary>
    /// 锟斤拷锟斤拷锟斤拷效锟斤拷小
    /// </summary>
    public void SetEffectAudioVolume(float volume)
    {
        EffectAudioVolume = volume;
        foreach (AudioSource audioSource in playingAudioList)
        {
            audioSource.volume = volume;
        }
    }
}
